package com.jyw.business.de.expand.service.impl;

import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.jyw.business.de.constant.DemandProcessConstant;
import com.jyw.business.de.constant.DemandStateConstant;
import com.jyw.business.de.domain.DeDemandInfo;
import com.jyw.business.de.expand.domain.dto.DeOrderAddDto;
import com.jyw.business.de.expand.service.IDeObstaclesService;
import com.jyw.business.de.service.IDeDemandInfoService;
import com.jyw.business.de.service.IDeDemandProcessService;
import com.jyw.business.obstacles.constant.OrderSourceConstant;
import com.jyw.business.obstacles.domain.ObsOrderInfo;
import com.jyw.business.obstacles.service.IObsOrderFaultService;
import com.jyw.common.exception.ServiceException;
import com.jyw.common.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service
public class DeObstaclesServiceImpl implements IDeObstaclesService {

    @Resource
    private IDeDemandInfoService deDemandInfoService;

    @Resource
    private IDeDemandProcessService processService;

    @Resource
    private IObsOrderFaultService orderFaultService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferOrder(DeOrderAddDto orderDto) {
        //获取需求
        DeDemandInfo info = deDemandInfoService.getById(orderDto.getDemandId());
        if(ObjectUtils.isEmpty(info)){
            throw new ServiceException("需求不存在");
        }
        if(!info.getDemandState().equals(DemandStateConstant.ALLOCATION)){
            throw new ServiceException("需求状态不为待分配,无法转工单");
        }

        //设置需求状态
        deDemandInfoService.lambdaUpdate()
                .eq(DeDemandInfo::getId, orderDto.getDemandId())
                .set(DeDemandInfo::getDemandState, DemandStateConstant.ORDER)
                .update();
        //设置来源工单转需求
        orderDto.getOrderAddDto().setSource(OrderSourceConstant.ITEM);
        ObsOrderInfo orderInfo = orderFaultService.add(orderDto.getOrderAddDto());
        //记录需求转工单操作流程
        processService.saveProcess(orderDto.getDemandId(), DemandProcessConstant.CONVERT_ORDER,orderInfo.getOrderNum());
    }
}
